
/*
 * @author Doan Tuan Anh 
 */

import javax.microedition.media.*;
import javax.microedition.media.control.*;

public class MusicPlayer implements PlayerListener {

  private Player myPlayer;
  private boolean myShouldPause;
  private boolean myGamePause;

  void pauseGame() {
    try {
      myGamePause = true;
      myPlayer.stop();
      myPlayer.close();
      myPlayer = null;
    } catch(Exception e) {

    }
  }
  
  synchronized void resumeGame() {
    try {
      myGamePause = false;
      if(! myShouldPause) {
	if(myPlayer == null) {
	  start();
	}
	// start the music.
	myPlayer.start();
      }
    } catch(Exception e) {
    }
  }

  synchronized void toggle() {
    try {
      myShouldPause = !myShouldPause;
      if(myShouldPause) {
	if(myPlayer != null) {
	  myPlayer.stop();
	}
      } else if(! myGamePause) {
	if(myPlayer == null) {
	  start();
	}
	myPlayer.start();
      }
    } catch(Exception e) {
    }
  }

  synchronized void requestStop() {
    try {
      myPlayer.stop();
      myPlayer.close();
    } catch(Exception e) {
    }
  }

  public void start() {
    try {
      myPlayer = Manager.createPlayer(getClass().getResourceAsStream("/angrybird.mp3"),"audio/mpeg");         
      myPlayer.realize(); 
      myPlayer.addPlayerListener(this);
      VolumeControl vc = (VolumeControl)myPlayer.getControl("VolumeControl");
      vc.setLevel(30);
    } catch(Exception e) {
    }
  }


  public void playerUpdate(Player player, String event, Object eventData) {
    if(event.equals(PlayerListener.END_OF_MEDIA)) {
      if((! myShouldPause) && (! myGamePause)) {
	try {
	  myPlayer.start(); 
	} catch(Exception e) {

	}
      }
    }
  }

}
